#include "musicslider.h"
#include "ui_musicslider.h"

#include <QMouseEvent>

MusicSlider::MusicSlider(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicSlider)
{
    ui->setupUi(this);

    currentPos = 0;
    moveSlider();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::setStep(float ratio)
{
    currentPos = maxWidth * ratio;
    moveSlider();
}

void MusicSlider::mouseMoveEvent(QMouseEvent *event)
{
    //检测: event->pos是否在MusicSlider的窗口矩形里面

    //QRect musicSliderRect = this->geometry();
    QRect musicSliderRect = QRect(0,0,width(),height());

    if (!musicSliderRect.contains(event->pos()))
    {
        return;
    }

    if (event->buttons() == Qt::LeftButton)
    {
        currentPos = event->pos().x();

        if (currentPos < 0)
        {
            currentPos = 0;
        }
        else if (currentPos > maxWidth)
        {
            currentPos = maxWidth;
        }

        moveSlider();

        return;
    }


    this->QWidget::mouseMoveEvent(event);

}

void MusicSlider::mousePressEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    moveSlider();
}

void MusicSlider::mouseReleaseEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    moveSlider();

    emit setMusicSilderPostion(ui->outLine->width() / (float)maxWidth);
}

void MusicSlider::moveSlider()
{
    ui->outLine->setGeometry(ui->outLine->x(),ui->outLine->y(),currentPos,ui->outLine->height());
}
